package com.moon.robot.Utils;


import com.alibaba.fastjson.JSON;
import com.forte.qqrobot.beans.messages.msgget.GroupMsg;
import com.forte.qqrobot.sender.MsgSender;

import com.moon.robot.pojo.GroupMsgs;
import com.moon.robot.pojo.Jianhuang;
import com.moon.robot.pojo.Reply;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
    public Utils() {
    }

    public static List<String> getMatcher(String source, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(source);
        List<String> end = new ArrayList<>();

        while (matcher.find()) {
            for (int i = 0; i <= matcher.groupCount(); i++) {
                if (matcher.group(i) != null) {
                    end.add(matcher.group(i));
                }

            }
        }
        if (end.size() == 0) {
            return null;
        } else {
            return end;
        }

    }

    public static Reply containsWordsAhoCorasick(String inputString, List<Reply> words) {
        for (Reply word : words) {
            boolean contains = inputString.contains(word.getMsg());
            if (contains) {
                return word;
            }
        }
        return null;
    }

    public static String DownLoadFile(String urlString) throws Exception {

        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String filename = "C:\\image/" + uuid + ".jpg";  //下载路径及下载图片名称
        File file = new File(filename);
        FileOutputStream os = new FileOutputStream(file, true);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
        return filename;
    }

    public static String getRandomStr(int length) {
        String str = "";
        int beginChar = 'a';
        int endChar = 'z';
        beginChar = 'a';
        endChar = 'z' + 10;
        // 生成随机类
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int tmp = (beginChar + random.nextInt(endChar - beginChar));
            // 大于'z'的是数字
            if (tmp > 'z') {
                tmp = '0' + (tmp - 'z');
            }
            str += (char) tmp;
        }

        return str;
    }


    public static String sendPostRequest(String requestUrl, String payload, String Cookie) {
        StringBuffer jsonString = new StringBuffer();
        HttpURLConnection connection = null;
        BufferedReader br = null;
        try {
            URL url = new URL(requestUrl);
            connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");

            connection.setRequestProperty("user-agent", "Mozilla/5.0 (compatible; MSIE 11.0; Windows NT 6.1; Trident/5.0)");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            connection.setRequestProperty("Cookie", Cookie);
            connection.setRequestProperty("origin", "https://qun.qq.com");
            connection.setRequestProperty("referer", "https://qun.qq.com/member.html");

            connection.setReadTimeout(300000);
            connection.setConnectTimeout(300000);

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            writer.write(payload);
            writer.close();
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String line;
            while ((line = br.readLine()) != null) {
                jsonString.append(line);
            }
            br.close();
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
            br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            String line;
            try {
                while ((line = br.readLine()) != null) {
                    jsonString.append(line);
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } finally {
            connection.disconnect();
            try {
                br.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return jsonString.toString();
    }


    public static String TimeStamp2Date(String timestampString, String formats) {
        Long timestamp = Long.parseLong(timestampString) * 1000;
        String date = new java.text.SimpleDateFormat(formats).format(new Date(timestamp));
        return date;
    }

    public static List<String> processing(String qq_name, int size, String gc, String bkn, String Cookie) throws Exception {
        //存放每个QQ详细数据
        List<String> olist = new ArrayList<String>();
        olist.add("uin" + "\t" + "role" + "\t" + "flag" + "\t" + "g" + "\t" + "join_time" + "\t" + "last_speak_time" + "\t" + "lv" + "\t" + "nick" + "\t" + "card" + "\t" + "qage" + "\t" + "tags" + "\t" + "rm" + "\t" + "mailbox");
        //控制偏移量
        int i = 0;
        //控制循环次数
        int j = 0;
        //控制是否跳出循环的boolean
        boolean judge = true;
        while (judge) {
            int st = i;            //from(开始)
            int end = i + 20;        //end(结束)

            String requestUrl = "http://qun.qq.com/cgi-bin/qun_mgr/search_group_members?gc=" + gc + "&st=" + st + "&end=" + end + "&sort=0&bkn=" + bkn;

            JSONObject json_all = JSONObject.fromObject(sendPostRequest(requestUrl, "", Cookie));
            if (json_all.get("mems") != null) {
                String qq_all = json_all.get("mems").toString();


                JSONArray json_qq = JSONArray.fromObject(qq_all);
                for (int le = 0; le < json_qq.size(); le++) {
                    JSONObject qq = JSONObject.fromObject(json_qq.get(le));
                    //把每个QQ转换成一条数据并存入List集合
                    String all = qq.getString("uin") + "\t" +
                            qq.getString("role") + "\t" +
                            qq.getString("flag") + "\t" +
                            qq.getString("g") + "\t" +
                            TimeStamp2Date(qq.getString("join_time"), "yyyy-MM-dd") + "\t" +
                            TimeStamp2Date(qq.getString("last_speak_time"), "yyyy-MM-dd") + "\t" +
                            qq.getString("lv") + "\t" +
                            qq.getString("nick") + "\t" +
                            qq.getString("card") + "\t" +
                            qq.getString("qage") + "\t" +
                            qq.getString("tags") + "\t" +
                            qq.getString("rm") + "\t" +
                            qq.getString("uin") + "@qq.com";
                    System.out.println(all);
                    olist.add(all);
                }
            }
            j++;    //控制循环次数
            if (j == size / 21) {
                judge = false;        //循环完毕后跳出循环
            } else {
                i += 21;
            }


            Thread.sleep(1500);
        }
        return olist;
    }

    public static String getBkn(String skey) {
        int p = 0;
        int hash = 5381;
        for (int i = 0, len = skey.length(); i < len; ++i) {
            hash += (hash << 5) + skey.charAt(i);
        }
        p = hash & 2147483647;
        String bkn = String.valueOf(p);
        return bkn;
    }


    public static boolean Appraisal(List<Jianhuang> simple, MsgSender sender, GroupMsg groupMsg) throws InterruptedException {
        if (simple == null || simple.size() < 1) {
            return false;
        }


        for (int i = simple.size() - 1; i >= 0; i--) {
            List<String> list2 = Utils.getMatcher(simple.get(i).getProbability(), "(E)");
            if (list2 != null && list2.get(1) != null) {
                simple.remove(i);
            }
        }


        for (int i = 0; i < simple.size(); i++) {
            List<String> list4 = Utils.getMatcher(simple.get(i).getClass_name(), "(艺术品色情)");
            if (list4 != null && list4.get(1) != null) {
                float v = Float.parseFloat(simple.get(i).getProbability());
                if (v >= 0.6) {
                    /* sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "[CQ:at,qq=" + groupMsg.getQQ() + "]" + "，该图片不合格，原因为：" + simple.get(i).getClass_name());*/
                    sender.SETTER.setMsgRecall(groupMsg.getId());
                    Thread.sleep(1000);
                    return false;
                }
            }

            List<String> list2 = Utils.getMatcher(simple.get(i).getClass_name(), "(色情)");
            if (list2 != null && list2.get(1) != null) {

                float v = Float.parseFloat(simple.get(i).getProbability());

                if (v >= 0.5) {
                    /*  sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "色情禁言十天");*/
                    /* sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "[CQ:at,qq=" + groupMsg.getQQ() + "]" + "，该图片不合格，原因为：" + simple.get(i).getClass_name());
                     */ //禁言
                    sender.SETTER.setMsgRecall(groupMsg.getId());
                    sender.SETTER.setGroupBan(groupMsg.getGroup(), groupMsg.getQQ(), 864000);
                    Thread.sleep(1000);
                    return false;
                }
            }
            List<String> list3 = Utils.getMatcher(simple.get(i).getClass_name(), "(性感)");
            if (list3 != null && list3.get(1) != null) {
                float v = Float.parseFloat(simple.get(i).getProbability());
                Integer time = 0;
                if (v >= 0.5) {
                    time = time + 3600;
                }
                if (v >= 0.6) {
                    time = time + 3600;
                }
                if (v >= 0.7) {
                    time = time + 7200;
                }
                if (v >= 0.8) {
                    time = time + 28800;
                }
                if (v >= 0.9) {
                    time = time + 43200;
                }
                if (v >= 0.5) {
                    sender.SETTER.setGroupBan(groupMsg.getGroup(), groupMsg.getQQ(), time);

                }
                return false;
            }
        }

        return true;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /*
        public static void addfile(String filename,String filepath) throws FileNotFoundException {



            String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = "LTAI4FnLEMz2aiZ1LrUmPJJx";
            String accessKeySecret = "BLTMTbOdoPyWG6XBvLB8MaGJFf0D8k";
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            File file = new File(filepath);
    // 上传文件流。
            InputStream inputStream = new FileInputStream(file);
            ossClient.putObject("yuejie1", filename, inputStream);
    // 关闭OSSClient。
            ossClient.shutdown();
        }

        public static String getUrl() {

    // Endpoint以杭州为例，其它Region请按实际情况填写。
            String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = "LTAI4FpWKR3KzuwJknL67P49";
            String accessKeySecret = "JSFhIHAqcDRTCNnCFaO6KSMFo9YARJ";
            String bucketName = "yuejie1";
            String objectName = "scripts32";

    // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    // 设置URL过期时间为1小时。
            Date expiration = new Date(new Date().getTime() + 300 * 1000);//五分钟
    // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
            URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);

    // 关闭OSSClient。
            ossClient.shutdown();


            return url.toString();
        }*/
    public static boolean uploadSC(String[] cmd, String path) throws Exception {

        File dir = new File(path);//此处是指定路径
        Process process = Runtime.getRuntime().exec(cmd, null, dir);


        if (process.waitFor() == 0) {
            System.out.println("一个");
        }

        if (process != null) {
            process.getOutputStream().close();
        }

      /*  InputStream in = process.getInputStream();
        while (in.read() != -1) {
            System.out.println(in.read());
        }
        in.close();
        process.waitFor();*/

        return true;

    }

    public static List<String> uploadFireFoxSend(String[] cmd, String path, Integer x) throws Exception {

        File dir = new File(path);//此处是指定路径
        List<String> a = new ArrayList<>();
        for (int i = 1; i <= x; i++) {
            System.out.println("开始上传");
            Process process = Runtime.getRuntime().exec(cmd, null, dir);
            process.waitFor();
            System.out.println("上传完成，开始解析返回信息");
            InputStream in = process.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line = null;
            StringBuffer b = new StringBuffer();
            while ((line = br.readLine()) != null) {
                b.append(line + "\n");
            }
            String url = b.toString();
            in.close();
            process.waitFor();
            a.add(url);
            System.out.println("上传完成" + url);
            if (process != null) {
                process.getOutputStream().close();
            }
        }

        return a;
    }

    public static String gbEncoding(final String gbString) {   //gbString = "测试"
        char[] utfBytes = gbString.toCharArray();   //utfBytes = [测, 试]
        String unicodeBytes = "";
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
            String hexB = Integer.toHexString(utfBytes[byteIndex]);   //转换为16进制整型字符串
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        /* System.out.println("unicodeBytes is: " + unicodeBytes);*/
        return unicodeBytes;
    }

    public static String GroupMsgToJson(GroupMsg groupMsg) {

        GroupMsgs groupMsgs = new GroupMsgs(groupMsg.getGroupCode(), groupMsg.getQQCode(), groupMsg.getPowerType().TO_STRING, groupMsg.getId(), groupMsg.getMsg(), groupMsg.getNickname(), groupMsg.getQQHeadUrl(), groupMsg.getRemark());

        com.alibaba.fastjson.JSONObject o = (com.alibaba.fastjson.JSONObject) JSON.toJSON(groupMsgs);

        o.put("type", "n");
        String string = JSON.toJSONString(o);
        return string;
    }
}